<?php

namespace app\api\controller\xiservice;

use app\common\controller\xiservice\XiserviceApi;
use addons\xiservice\controller\WeixinMini;
use app\common\model\xiservice\User as XiserviceUser;
use app\common\model\xiservice\Service;
use app\common\model\xiservice\Refuse;
use app\common\model\xiservice\Wxtemplate;
use fast\Http;
use think\Exception;
use think\Db;

use AlibabaCloud\SDK\Dyplsapi\V20170525\Models\BindAxnRequest;

use AlibabaCloud\SDK\Dyplsapi\V20170525\Dyplsapi;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dyplsapi\V20170525\Models\BindAxbRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\common\model\xiservice\Area;

/**
 * 订单模块
 */
class Order extends XiserviceApi
{
    protected $noNeedLogin = ['analog_notify'];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\xiservice\Order();
    }

    /**
     * @ApiTitle (用户订单列表信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/list)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="checkinfo", type="integer", description="订单状态")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function list()
    {
        $checkinfo = $this->request->request('checkinfo', 0);
        
        $keyword = $this->request->request('keyword');
        $order_type = $this->request->request('order_type','10');

        $whereStatus = $this->model->getCheckinfoStatus($checkinfo);


        $where['order.order_no|service.name'] = ['like', '%' . $keyword . '%'];
        
        

        $list = $this->model->with(['service' => function ($query) {
            $query->withField('id,name,image,basicnums,salenums,saleprice');
        }, 'worker' => function ($query) {
            $query->withField('id,username,avatar');
        }
        ])
            ->where('order.user_id', $this->auth->id)
            ->where('order.order_type', $order_type)
            // ->where('order.order_type',10)
            ->where($whereStatus)
            ->where($where)
            ->order('createtime desc')
            ->paginate();
       

        $this->success('查询成功', $list);
    }

    public function pxlist()
    {
        $checkinfo = $this->request->request('checkinfo', 0);
        $userid = $this->auth->id;
   
        if($checkinfo >0)
        {
            $list = Db::query("select *,DATE_FORMAT(FROM_UNIXTIME(exam_time), '%Y-%m-%d %H:%i:%s') AS formatted_exam_time from fa_train_order where status=:status and user_id=:user_id",['status'=>$checkinfo,'user_id'=>$userid]);
        }
        else
        {
            $list = Db::query("select *,DATE_FORMAT(FROM_UNIXTIME(exam_time), '%Y-%m-%d %H:%i:%s') AS formatted_exam_time from fa_train_order where user_id=:user_id",['user_id'=>$userid]);
        }

       
        $this->success('查询成功', $list);
    }

    /**
     * @ApiTitle (用户订单列表信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/order_num)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="checkinfo", type="integer", description="订单状态")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function order_num()
    {
        $keyword = $this->request->request('keyword');

        $checkinfo = $this->count_num(0, $keyword, $this->auth->id);
        $checkinfo1 = $this->count_num(1, $keyword, $this->auth->id);
        $checkinfo2 = $this->count_num(2, $keyword, $this->auth->id);
        $checkinfo3 = $this->count_num(3, $keyword, $this->auth->id);
        $checkinfo4 = $this->count_num(4, $keyword, $this->auth->id);
        $checkinfo5 = $this->count_num(5, $keyword, $this->auth->id);
        $checkinfo7 = $this->count_num(7, $keyword, $this->auth->id);

        $data['checkinfo'] = $checkinfo;
        $data['checkinfo1'] = $checkinfo1;
        $data['checkinfo2'] = $checkinfo2;
        $data['checkinfo3'] = $checkinfo3;
        $data['checkinfo7'] = $checkinfo7;//质保单
        $data['checkinfo4'] = $checkinfo4;
        $data['checkinfo5'] = $checkinfo5;

        $this->success('查询成功', $data);
    }

    /*
    ** 查询订单数量
     */
    public function count_num($checkinfo, $keyword, $uid)
    {
        $whereStatus = $this->model->getCheckinfoStatus($checkinfo);
        $where['order.order_no|service.name'] = ['like', '%' . $keyword . '%'];
        $num = $this->model->with(['service' => function ($query) {
            $query->withField('id,name,image,basicnums,salenums,saleprice');
        }, 'worker' => function ($query) {
            $query->withField('id,username,avatar');
        }
        ])
            ->where('order.user_id', $uid)
            ->where('order.order_type', 10)
            ->where($whereStatus)
            ->where($where)
            ->count();
        return $num;
    }


    /**
     * @ApiTitle (订单详细信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/detail)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function detail()
    {
        $id = $this->request->request('id');
        $data = $this->model->with(['service' => function ($query) {
            $query->withField('id,name,image,basicnums,salenums,saleprice');
        }, 'user' => function ($query) {
            $query->withField('virtual_number');
        }])
            ->where('order.user_id', $this->auth->id)
            ->where('order.id', $id)
            ->find();

        $workerid=  $data['worker_id'];
        $serviceuser = Db::query('select f.*,f1.virtual_number from fa_xiservice_user f inner join fa_user f1 on f1.id=f.user_id
        where f.id=:id;',['id'=> $workerid]);
        if($serviceuser)
        {
            $data['worker'] =  $serviceuser[0];
        }
        $paytime = $data['pay_time']+ 10 * 60;
        $timestamp_plus_30_minutes = time() ;
        $data['isshowphone']=false;
        if($paytime< $timestamp_plus_30_minutes)
        {
            $data['isshowphone']=true;
        }
        if(!$data['pay_time'])
        {
            $data['isshowphone']=false;
        }
        $this->success('查询成功', $data);
    }
    public function detailexpert()
    {
        $id = $this->request->request('id');
        $data = $this->model->with(['service' => function ($query) {
            $query->withField('id,name,image,basicnums,salenums,saleprice');
        }, 'user' => function ($query) {
            $query->withField('virtual_number,contact_name,service_category_id');
        }])
            ->where('order.user_id', $this->auth->id)
            ->where('order.id', $id)
            ->find();

        $userinfo =  Db::name('xiservice_user')->where('id', $data['worker_id'])->find();
        $service_category_id = $userinfo['service_category_id'];       
        $categoryModel = Db::name('xiservice_service_category')->where('id',$service_category_id)->find();
        $data['categoryname']= $categoryModel['name'];
        $data['servername']= $userinfo['contact_name'];

        $this->success('查询成功', $data);
    }


    
    /**
     * @ApiTitle (服务人员订单列表信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/worker_orderlist)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="checkinfo", type="integer", description="订单状态")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function worker_orderlist()
    {
        $userInfo= Db::name('xiservice_user')->where(['user_id'=>$this->auth->id])->find();
        $checkinfo = $this->request->request('checkinfo', 0);
        $order_type = $this->request->request('order_type', '10');

        $keyword = $this->request->request('keyword');
        $whereStatus = $this->model->getWorkerCheckinfoStatus($checkinfo);
        $where['order.order_no|service.name'] = ['like', '%' . $keyword . '%'];
        $list = $this->model->with(['service' => function ($query) {
            $query->withField('id,name,image,basicnums,salenums,saleprice');
        }, 'user' => function ($query) {
            $query->withField('id,username,avatar,virtual_number');
        }
        ])
            ->where('order.worker_id', $userInfo['id'])
            ->where('order.order_type',$order_type)
            ->where('order.citytxt',$userInfo['citytxt'])

            ->where($whereStatus)
            ->where($where)
            ->order('createtime desc')
            ->paginate();

            // $array = json_decode($list, true);
        // if($list && $list['data'])
        // {
        //    foreach($list['data'] as $item)
        //    {
        //     $item['test']='1';
        //    }
        // }
        $this->success('查询成功', $list);
    }


    /**
     * @ApiTitle (服务人员订单数量信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/worker_orderlist)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="checkinfo", type="integer", description="订单状态")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function worker_ordernum()
    {

        $keyword = $this->request->request('keyword');

        $checkinfo = $this->count_workernum(0, $keyword, $this->auth->id);
        $checkinfo1 = $this->count_workernum(1, $keyword, $this->auth->id);
        $checkinfo2 = $this->count_workernum(2, $keyword, $this->auth->id);
        $checkinfo3 = $this->count_workernum(3, $keyword, $this->auth->id);
        $checkinfo4 = $this->count_workernum(4, $keyword, $this->auth->id);
        $checkinfo5 = $this->count_workernum(5, $keyword, $this->auth->id);
        $checkinfo6 = $this->count_workernum(6, $keyword, $this->auth->id);//质保中

        $data['checkinfo'] = $checkinfo;
        $data['checkinfo1'] = $checkinfo1;
        $data['checkinfo2'] = $checkinfo2;
        $data['checkinfo3'] = $checkinfo3;
        $data['checkinfo4'] = $checkinfo4;
        $data['checkinfo5'] = $checkinfo5;
        $data['checkinfo6'] = $checkinfo6;

        $this->success('查询成功', $data);
    }

    /*
    ** 查询服务人员订单数量
     */
    public function count_workernum($checkinfo, $keyword, $uid)
    {
        $whereStatus = $this->model->getWorkerCheckinfoStatus($checkinfo);
        $where['order.order_no|service.name'] = ['like', '%' . $keyword . '%'];
        $num = $this->model->with(['service' => function ($query) {
            $query->withField('id,name,image,basicnums,salenums,saleprice');
        }, 'user' => function ($query) {
            $query->withField('id,username,avatar');
        }
        ])
            ->where('order.worker_id', $uid)
            ->where($whereStatus)
            ->where($where)
            ->count();
        return $num;
    }


    /**
     * @ApiTitle (订单详细信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/worker_orderdetail)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function worker_orderdetail()
    {
        $id = $this->request->request('id');
        
        $data = $this->model->with(['service' => function ($query) {
            $query->withField('id,name,image,basicnums,salenums,saleprice,lowprice');
        }, 'user' => function ($query) {
            $query->withField('id,username,avatar,mobile,virtual_number');
        }])->where('order.id', $id)
            ->find();
       
     $userId = $this->auth->id;    

            
    $quoteinfo = Db::name('xiservice_user_quote')->where('order_id',$id)->where('user_id',$userId)->find();
   
    //     print_r($quoteinfo);
        
        // die;
            if(empty($quoteinfo)){
                $quoteinfo['amount'] = 0;
                $data['quote_amount']=0;
            }else{
                $data['quote_amount'] = $quoteinfo['amount'];
            }
            
            $data['to_money'] = $quoteinfo['amount'] + $data['visit_money'];

        if ($data) {
            $refuse = Refuse::where("user_id", $this->auth->id)
                ->where("order_id", $id)
                ->find();
            if ($refuse) {
                $data['refuse'] = 1;
            } else {
                $data['refuse'] = 0;
            }
        $paytime = $data['pay_time']+ 5 * 60;
        $timestamp_plus_30_minutes = time() ;
        $data['isshowphone']=false;
        if($paytime< $timestamp_plus_30_minutes)
        {
            $data['isshowphone']=true;
        }
        }

        $data['areaprice'] = $data['service']['lowprice'] * $data['area'];
  
        $this->success('查询成功', $data);
    }


    /**
     * @ApiTitle (任务大厅订单列表信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/mission_orderlist)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="type", type="integer", description="状态")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function mission_orderlist()
    {
        $type = $this->request->request('type');
        $keyword = $this->request->request('keyword');
        $order_type = $this->request->request('order_type', '10');

        $userId = $this->auth->id;
        
        //抢单模式
            $worker = XiserviceUser::where("user_id", $this->auth->id)->find();
            $refuseIds = Refuse::where('user_id', $this->auth->id)->column('order_id');
            $list = $this->model->with(['service' => function ($query) {
                $query->withField('id,name,image,basicnums,salenums,saleprice,service_category_id');
            }, 'user' => function ($query) {
                $query->withField('id,username,avatar');
            }
            // echo "<pre>";
            // print_r($keyword);die;
            ])
               //->where($a['id'] = Db::name('xiservice_service_category')->where('id','service.service_category_id')->find(), 'in', $worker['service_category_id'])
                ->where('order.task_mode', 0)
                ->where('order.worker_id', 0)
                ->where('order.order_type', $order_type)
                ->where('order.citytxt', $worker['citytxt'])
                ->where('order.id', 'not in', $refuseIds)
                ->where('order_status', 20)
                ->order('createtime desc')
                ->paginate();
                foreach($list as $item)
                {
                    $item['service_amount']=0;
                    if($item['service_id'] && $item['service_id'] > 0)
                    {
                        $server_id = $item['service_id'];
                        $order_id = $item['id'];
                        $quote =Db::query('select * from fa_xiservice_user_quote where order_id=:order_id and user_id=:user_id;',
                        ['order_id'=>$order_id,'user_id'=>$userId]);
                        if( $quote && $quote[0])
                        {
                            $item['service_amount']=$quote[0]['amount'];
                        }
                       
                    }
                  
                }
        $this->success('查询成功', $list);
    }


    /**
     * @ApiTitle (展示下单详细信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/show)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="address_id", type="integer", description="地址id")
     * @ApiParams  (name="service_id", type="integer", description="服务id")
     * @ApiParams  (name="coupon_id",  type="integer", description="优惠券id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function show()
    {
        $addressId = $this->request->request('address_id', 0);
        $serviceId = $this->request->request('service_id', 0);
        $couponId = $this->request->request('coupon_id', 0);
        $servicenums = $this->request->request('servicenums', 1);
        $workerId = $this->request->request('worker_id', 0);
        if (!$serviceId) {
            $this->error('参数错误', []);
        }
        $result = $this->model->orderShow($this->auth->id, $addressId, $serviceId, $couponId, $servicenums, $workerId);
        if (!$result['status']) {
            $this->error($result['msg'], []);
        }
         $retentionlist = Db::name('xiservice_service')->where('id',$serviceId)->find();
         $result['data']['retentionlist']=$retentionlist['quality_day'];
        $this->success('查询成功', $result['data']);
    }

    public function updateorderamount()
    {
        $serviceId = $this->request->request('service_id');
        $serviceAmount = $this->request->request('service_amount', 0.1);
        $order_id = $this->request->request('order_id',133); 
        if (!$serviceId) {
            $this->error('参数错误', []);
        }
        Db::execute('update fa_xiservice_order set order_status=10,
        worker_id=:worker_id,total_money=:serviceamount,pay_money=:pay_money where id=:id;',[
            'worker_id'=> $serviceId,
            'pay_money'=>$serviceAmount,
            'serviceamount'=> $serviceAmount,
            'id'=>$order_id
        ]);
        $worker = XiserviceUser::where("id",  $serviceId)->find();
        $order = $this->model->where('id', $order_id)->find();
   

        $order['user_id']= $worker['user_id'];
        $order['quote_amount']=$serviceAmount;
            //  //推送订阅消息
            //  $msg = new \app\common\model\xiservice\Message();
            //  $msg->sendOrderMessage($order, 8);
             $userA = Db::name('user')->where(['id'=>$this->auth->id])->find();
             $userB = Db::name('user')->where(['id'=>$worker['user_id']])->find();
             $this->bindAxb($userA['mobile'],$userB['mobile'],$userB['id'],$userA['id']);
            //  $this->bindAxb($userB['mobile'],$userA['mobile'],$userA['id']);
        $this->success('处理成功', 1);
    }

    public function bindAxb($phoneNoA,$phoneNoB,$useridB,$useridA)
    {
        $config = new Config([
            "accessKeyId" => "LTAI5tJ4dtHvxJXpDAJTRuFN",
            "accessKeySecret" => "9Aafg08e9GCVFGB9ZJhYMSvYBzRA0U"
        ]);
        $config->endpoint = "dyplsapi.aliyuncs.com";
        $client = new Dyplsapi($config);
        $timestamp_plus_5_minutes = time() + 60 * 60;
        $added_time = date('Y-m-d H:i:s',$timestamp_plus_5_minutes);
        $bindAxnRequest = new BindAxnRequest([
            "poolKey" => "FC100000180222320",
            "phoneNoA" =>$phoneNoA,
            "phoneNoB" => $phoneNoB,
            "expiration" => $added_time
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $response= $client->bindAxnWithOptions($bindAxnRequest, $runtime);
            $json = json_encode($response);
            $array = json_decode($json, true);

            $json2 = json_encode($array['body']);
            if($array && $array['body'] && $array['body']['secretBindDTO'])
            {
                $virtual_number = $array['body']['secretBindDTO']['secretNo'];
                Db::name('xiservice_user')->where(['user_id'=>$useridB])->update(["virtual_number"=>$virtual_number]);
                Db::name('xiservice_user')->where(['user_id'=>$useridA])->update(["virtual_number"=>$virtual_number]);
            }
        }
        catch (\Exception $error) {
           
        }
    }

    public function updateordercheckimages()
    {
        $check_images = $this->request->request('check_images');
        if(empty($check_images)){
            $this->error('请上传服务场所照片', []);
        }
        $order_status = $this->request->request('order_status');
        $arrive_address = $this->request->request('arrive_address');
        $order_id = $this->request->request('order_id');
        $data = Db::name('xiservice_order')->where('id',$order_id)->find();
        // die;

        if (!$order_id) {
            $this->error('参数错误', []);
        }
        Db::execute('update fa_xiservice_order set order_status=:order_status,
        check_images=:check_images,arrive_address=:arrive_address where id=:id;',[
            'order_status'=> $order_status,
            'check_images'=>$check_images,
            'id'=>$order_id,
            'arrive_address'=> $arrive_address
        ]);       
        $this->success('处理成功', 1);
    }


    public function getgoodlist()
    {
        $id = $this->request->request('id');
        //$goodList = Db::name('goods')->select();
        $goodArry=[];
        $goodArry[]='国产药';
        $goodArry[]='进口药';
        // foreach( $goodList as $item)
        // {
        //     $goodArry[]=$item['goods_name'];
        // }
        $this->success('查询成功', $goodArry);
    }

    /**
     * @ApiTitle (展示下单详细信息)
     * @ApiMethod (Post)
     * @ApiRoute (/api/xiservice.order/create)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function create()
    {
        $addressId = $this->request->request('address_id', 0);
        $workerId = $this->request->request('worker_id', 0);
        $serviceId = $this->request->request('service_id', 0);
        $retention_amount = $this->request->request('retention_amount', 0);
        $servicenums = $this->request->request('servicenums', 1);
        $couponId = $this->request->request('coupon_id', 0);
        $serviceStartTime = $this->request->request('service_start_time');
        $serviceDesc = $this->request->request('service_desc', '');
        $serviceDescImages = $this->request->request('service_desc_images', '');
        $remark = $this->request->request('remark', '');
        $checkContract = $this->request->request('check_contract', 0);
        $region = $this->request->request('region', 0);
        $area = $this->request->request('area', 0);
        $bytype = $this->request->request('bytype', 0);
        $fwpc = $this->request->request('fwpc', 0);
        $fwsj = $this->request->request('fwsj', 0);
        $tax_email = $this->request->request('tax_email', 0);
        $service_category_id = $this->request->request('service_category_id', 0);
        if($area){
            $area = $area;    
        }else{
            $area = 50;
        }
        $tax_title = $this->request->request('tax_title', '');
        $tax_no = $this->request->request('tax_no', '');
        $goodname = $this->request->request('goodname', '');
        if (!$addressId) {
            $this->error('地址信息错误', []);
        }
        if (!$serviceId) {
            $this->error('参数错误', []);
        }
        if (!$serviceStartTime) {
            $this->error('请选择开始时间', []);
        }

        //判断服务人员工作时间
        if ($workerId) {
            //判断服务人员服务人员在忙
            $scheduleModel = new \app\common\model\xiservice\Schedule;

            $service = Service::where('id', $serviceId)->find();
            //计算duration
            $service_duration = 30;
            if ($service['service_time_type'] == 2) {
                //自选时长
                $service_duration = $service['service_time_unit'] * $servicenums;
            } else if ($service['service_time_type'] == 1) {
                //固定时长
                $service_duration = $service['service_duration'];
            } else {
                //无时长
                $service_duration = 30;
            }

            $reserve_time = $serviceStartTime;
            $count = $service_duration / 30;
            //时间分段
            $time_arr = [];
            array_push($time_arr, $reserve_time);
            if ($count > 1) {
                for ($i = 0; $i < $count; $i++) {
                    $time = $reserve_time + 30 * 60 * ($i + 1);
                    array_push($time_arr, $time);
                }
            } else {
                array_push($time_arr, $reserve_time + 30 * 60);
            }
            $check = $scheduleModel->where('user_id', $workerId)->where('rest_timestamp', 'in', $time_arr)->find();
            if ($check) {
                $this->error('当前时间服务人员在忙~请选择其他时间!', []);
            }
        }

        $result = $this->model->orderShow($this->auth->id, $addressId, $serviceId, $couponId, $servicenums, $workerId);
        if (!$result['status']) {
            $this->error($result['msg'], []);
        }
        //判断服务类型 是否选择服务人员  
        if ($result['data']['chose_type'] == 1) {
            if (!$workerId) {
                $this->error('请选择服务人员', []);
            }
            $result['data']['worker_id'] = $workerId;
        }
        $lat = $result['data']['lat'];
        $lng = $result['data']['lng'];

        $areaInfo =Area::where('level',3)->field("*,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - ".$lat." * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(".$lat." * pi() / 180) * pow(sin((lng * pi() / 180 - ".$lng." * pi() / 180) / 2),2))) * 1000) as distance")
        ->order('distance asc')
        ->find();
        if($areaInfo){
            $provinceInfo = Area::where('id',$areaInfo['pid'])->find();
            if($provinceInfo){
                $result['data']['citytxt']= $provinceInfo['name'];
            }
        }

        $result['data']['service_desc'] = $serviceDesc;
        $result['data']['service_desc_images'] = $serviceDescImages;
        $result['data']['service_start_time'] = $serviceStartTime;
        $result['data']['remark'] = $remark;
        $result['data']['have_contract'] = $checkContract;
        // $result['data']['retention_amount']=$retention_amount;
        $result['data']['area']=$area;
        $result['data']['region']=$region;
        $result['data']['tax_title']=$tax_title;
        $result['data']['tax_no']=$tax_no;
        $result['data']['good_name']=$goodname;
        $result['data']['bytype']=$bytype;
        $result['data']['fwpc']=$fwpc;
        $result['data']['fwsj']=$fwsj;
        $result['data']['tax_email']=$tax_email;
        $result['data']['service_category_id']=$service_category_id; 

        $res = $this->model->createOrder($result['data'], $this->auth->id);
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $orderInfo = $this->model->where('id', $res['data'])->find();


           //推送订阅消息
        $msg = new \app\common\model\xiservice\Message();
        $msg->sendOrderMessage($orderInfo, 9);


        //判断议价情况 是否先支付 还是后支付
        if ($orderInfo['bargain'] == 0) {
            //固定价格
            //先支付上门费+服务费
            if ($orderInfo['pay_money'] > 0) {
                //创建微信订单 进行支付
                $user = XiserviceUser::where('user_id', $this->auth->id)->find();
                $num = mt_rand(100, 999);
                $order_no = $orderInfo['order_no'] . '_' . $num;
                $price = $orderInfo['pay_money'];
                //测试 一分钱支付
                //$price = 0.01;
                $orderpay = array(
                    'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
                    'out_trade_no' => $order_no,//订单号
                    'body' => $orderInfo['service']['name'],//
                    'total_fee' => $price,//支付金额，这边传单位为元的就可以。
                    'openid' => $user['mini_openid'],//用户openID
                );

                $wx = new WeixinMini();
                $ret = $wx->union_order($orderpay);
                if ($ret['status']) {
                    $this->success('创建微信订单成功', ['wxconfig' => $ret['wxconfig'], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
                } else {
                    $this->error("创建微信订单失败", ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
                }
            } else {
                //直接进入 购买成功的方法里
                $res = $this->model->changeOrderStatus($orderInfo['id'], 'payed');
                if (!$res['status']) {
                    $this->error($res['msg']);
                }
                $this->success('支付成功', ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);

            }

        } else {
            //议价
            $pay_money = 0;
            $text = '';
            if($orderInfo['visit_pay_status'] == 0) {
                $pay_money = $orderInfo['visit_money'];
                $text = '上门费';
            } else if($orderInfo['pay_status'] == 10) {
                $pay_money = $orderInfo['pay_money'];
            }

            if ($pay_money>0) {
                //创建微信订单 进行支付上门费
                $user = XiserviceUser::where('user_id', $this->auth->id)->find();
                $num = mt_rand(100, 999);
                $order_no = $orderInfo['order_no'] . '_' . $num;
                $price = $pay_money;

                $orderpay = array(
                    'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
                    'out_trade_no' => $order_no,//订单号
                    'body' => $orderInfo['service']['name'] . $text,
                    'total_fee' => $price,//支付金额，这边传单位为元的就可以。
                    'openid' => $user['mini_openid'],//用户openID
                );

                $wx = new WeixinMini();
                $ret = $wx->union_order($orderpay);
                if ($ret['status']) {
                    $this->success('创建微信订单成功', ['wxconfig' => $ret['wxconfig'], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $pay_money, 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
                } else {
                    $this->error("创建微信订单失败", ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $pay_money, 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
                }
            } else {
                //直接进入 购买成功的方法里
                $res = $this->model->changeOrderStatus($orderInfo['id'], 'payedall');
                $this->success('创建订单成功', ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $pay_money, 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);

            }
        }
    }

    public function createexpert()
    {
        $serviceDesc = $this->request->request('service_desc', '');
        $addr = $this->request->request('addr', '');
        $lat = $this->request->request('lat', '');
        $lng = $this->request->request('lng', '');

        $areaInfo =Area::where('level',3)->field("*,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - ".$lat." * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(".$lat." * pi() / 180) * pow(sin((lng * pi() / 180 - ".$lng." * pi() / 180) / 2),2))) * 1000) as distance")
        ->order('distance asc')
        ->find();
        if($areaInfo){
            $provinceInfo = Area::where('id',$areaInfo['pid'])->find();
            if($provinceInfo){
                $result['data']['citytxt']= $provinceInfo['name'];
                $result['data']['province_id'] = $provinceInfo['pid'];
            }
            $result['data']['city_id'] = $areaInfo['pid'];
            $result['data']['area_id'] = $areaInfo['id'];
        }
        $serviceDescImages = $this->request->request('service_desc_images', '');
        $remark = $this->request->request('remark', '');
        $checkContract = $this->request->request('check_contract', 0);
        $result['data']['service_desc'] = $serviceDesc;
        $result['data']['addr'] = $addr;
        $result['data']['lat'] = $lat;
        $result['data']['lng'] = $lng;
        $result['data']['order_type'] = '20';

        $result['data']['service_id']=0;
        $result['data']['service_desc_images'] = $serviceDescImages;
        $result['data']['remark'] = $remark;
        $result['data']['have_contract'] = $checkContract;
        $result['data']['pay_money'] =1;
        $result['data']['total_money'] =1;

        $result['data']['worker_id']=0;
        $result['data']['task_mode']=0;
        $result['data']['order_status']=40;
        // $result['data']['retention_amount']=$retention_amount;
        $res = $this->model->createOrder($result['data'], $this->auth->id);
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $orderInfo = $this->model->where('id', $res['data'])->find();


           //推送订阅消息
        // $msg = new \app\common\model\xiservice\Message();
        // $msg->sendOrderMessage($orderInfo, 10);


         //创建微信订单 进行支付
         $user = XiserviceUser::where('user_id', $this->auth->id)->find();
         $num = mt_rand(100, 999);
         $order_no = $orderInfo['order_no'] . '_' . $num;
         $price = $orderInfo['pay_money'];
         //测试 一分钱支付
         $price = 0.01;
         $orderpay = array(
             'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
             'out_trade_no' => $order_no,//订单号
//             'body' => $orderInfo['service']['name'],//
             'body' => '专家下单',//
             'total_fee' => $price,//支付金额，这边传单位为元的就可以。
             'openid' => $user['mini_openid'],//用户openID
         );

         $wx = new WeixinMini();
         $ret = $wx->union_order($orderpay);
         if ($ret['status']) {
             $this->success('专家订单创建成功', ['wxconfig' => $ret['wxconfig'], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
         } else {
             $this->error("专家订单创建失败", ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
         }
    }

    /**
     * @ApiTitle (获取订单支付参数)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/payorder)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function payconfig()
    {
        $id = $this->request->request('id');
        $orderInfo = $this->model->where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('订单信息错误', []);
        }
        // if ($orderInfo ['order_status'] != '10') {
        //     $this->error('订单状态错误', []);
        // }
        if ($orderInfo['bargain'] == 0) {
            //不议价
            if ($orderInfo['pay_money'] > 0) {
                //创建微信订单 进行支付
                $user = XiserviceUser::where('user_id', $this->auth->id)->find();
                $num = mt_rand(100, 999);
                $order_no = $orderInfo['order_no'] . '_' . $num;
                $price = $orderInfo['pay_money'];
                //测试 一分钱支付
                //$price = 0.01;
                $orderpay = array(
                    'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
                    'out_trade_no' => $order_no,//订单号
                    'body' => $orderInfo['service']['name'],//
                    'total_fee' => $price,//支付金额，这边传单位为元的就可以。
                    'openid' => $user['mini_openid'],//用户openID
                );

                $wx = new WeixinMini();
                $ret = $wx->union_order($orderpay);
                if ($ret['status']) {
                    $this->success('创建微信订单成功', ['wxconfig' => $ret['wxconfig'], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
                } else {
                    $this->error("创建微信订单失败", ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
                }
            } else {
                //直接进入 购买成功的方法里
                $res = $this->model->changeOrderStatus($orderInfo['id'], 'payed');
                if (!$res['status']) {
                    $this->error($res['msg']);
                }
                $this->success('支付成功', ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);

            }
        } else {
            $pay_money = 0;
            $text = '';
            if($orderInfo['visit_pay_status'] == 0) {
                $pay_money = $orderInfo['visit_money'];
                $text = '上门费';
            } else if($orderInfo['pay_status'] == 10) {
                $pay_money = $orderInfo['pay_money'];
            }

            if ($pay_money > 0) {
                //创建微信订单 进行支付上门费
                $user = XiserviceUser::where('user_id', $this->auth->id)->find();
                $num = mt_rand(100, 999);
                $order_no = $orderInfo['order_no'] . '_' . $num;
                $price = $pay_money;

                $orderpay = array(
                    'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
                    'out_trade_no' => $order_no,//订单号
                    'body' => $orderInfo['service']['name'] . $text,
                    'total_fee' => $price,//支付金额，这边传单位为元的就可以。
                    'openid' => $user['mini_openid'],//用户openID
                );

                $wx = new WeixinMini();
                $ret = $wx->union_order($orderpay);

                if ($ret['status']) {
                    $this->success('创建微信订单成功', ['wxconfig' => $ret['wxconfig'], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['visit_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
                } else {
                    $this->error("创建微信订单失败", ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['visit_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
                }
            } else {
                //直接进入 购买成功的方法里
                $res = $this->model->changeOrderStatus($orderInfo['id'], 'payedall');
                $this->success('创建订单成功', ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
            }
        }
    }

    /**
     * @ApiTitle (订单支付)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/payorder)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function payorder()
    {
        $id = $this->request->request('id');
        $orderInfo = $this->model->where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('订单信息错误', []);
        }
        if ($orderInfo['bargain'] == 0) {
            $this->error('订单信息错误', []);
        }
        if ($orderInfo['order_status'] == 20) {
            $this->error('订单已支付', []);
        }
        //创建微信订单 进行支付
        $user = XiserviceUser::where('user_id', $this->auth->id)->find();
        //$num = mt_rand(100, 999);
        $order_no = $orderInfo['order_no'];
        $price = $orderInfo['total_money'];
        // echo "<pre>";
        // print_r($price);die;
        $orderpay = array(
            'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
            'out_trade_no' => $order_no,//订单号
            //'body' => $orderInfo['service']['name'],//
            'body' => '下单订单',//
            'total_fee' => $price,//支付金额，这边传单位为元的就可以。
            'openid' => $user['mini_openid'],//用户openID
        );

        $wx = new WeixinMini();
        $ret = $wx->union_order($orderpay);

        if ($ret['status']) {
            $this->success('创建微信订单成功', ['wxconfig' => $ret['wxconfig'], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['total_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
        } else {
            $this->error("创建微信订单失败", ['wxconfig' => [], 'chose_type' => $orderInfo['chose_type'], 'bargain' => $orderInfo['bargain'], 'pay_money' => $orderInfo['total_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
        }
    }

    /**
     * @ApiTitle (取消订单信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/cancel)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function cancel()
    {
        $id = $this->request->request('id');
        $order = $this->model->where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
        // $time = time();
        // $c = $order['service_start_time'] - $time;
        // if ($c < 10800) {
        //     $this->error('需要在预约时间提前3小时才能取消!', []);
        // }
        if ($order['transaction_id']) {
            $wxpayconfig = config('xiservice.wxpayment');
            if (isset($wxpayconfig['apiclient_cert'])) {
                if (!$wxpayconfig['apiclient_cert']) {
                    $this->error('请先配置商户证书!', []);
                }
            } else {
                $this->error('请先配置商户证书!', []);
            }
        }
        $res = $this->model->changeOrderStatus($id, 'cancel');
        if (!$res['status']) {
            $this->error($res['msg']);
        }

        $this->success('取消成功', []);
    }
    public function acceptorder()
    {
        $id = $this->request->request('id');
        $order = $this->model->where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
        $res = $this->model->changeOrderStatus($id, 'finished');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $this->success('验收成功', []);
    }
    public function orderdiagnose()
    {
        $id = $this->request->request('id');        
        $insect_name = $this->request->request('insect_name');        
        $insect_hazard = $this->request->request('insect_hazard');
        $insect_remark = $this->request->request('insect_remark');
        $userid = $this->auth->id;
        $order = $this->model->where('id', $id)->find();
        if (!$order) {
            $this->error('此订单已被其他专家诊断，请勿重复诊断', []);
        }
        $userInfo= Db::name('xiservice_user')->where(['user_id'=>$this->auth->id])->find();
        if($order['worker_id']>0)
        {
            $this->error('订单已被诊断', []);
        }
        Db::execute('update fa_xiservice_order set order_status=50,
        worker_id=:worker_id,insect_name=:insect_name,insect_hazard=:insect_hazard,insect_remark=:insect_remark where id=:id;',[
            'worker_id'=> $userInfo['id'],
            'id'=>$id,
            'insect_name'=>$insect_name,
            'insect_hazard'=>$insect_hazard,
            'insect_remark'=>$insect_remark,
        ]);
        $res = $this->model->changeOrderStatus($id, 'diagnose');
        $this->success('诊断成功', []);
    }
    /**
     * @ApiTitle (修改订单时间信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/change)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiParams  (name="service_start_time", type="integer", description="上门时间")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function change()
    {
        $id = $this->request->request('id');
        $serviceStartTime = $this->request->request('service_start_time');
        $servicenums = $this->request->request('service_num');

        $order = $this->model->where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
        $time = time();
        $c = $order['service_start_time'] - $time;
        if ($c < 3600) {
            $this->error('需要在原预约时间提前1小时修改!', []);
        }
        if ($order['change_status'] == 1) {
            $this->error('超过订单修改时间最大次数!', []);
        }
        //判断服务人员服务人员在忙
        $scheduleModel = new \app\common\model\xiservice\Schedule;

        $service = Service::where('id', $order['service_id'])->find();
        //计算duration
        $service_duration = 30;
        if ($service['service_time_type'] == 2) {
            //自选时长
            $service_duration = $service['service_time_unit'] * $servicenums;
        } else if ($service['service_time_type'] == 1) {
            //固定时长
            $service_duration = $service['service_duration'];
        } else {
            //无时长
            $service_duration = 30;
        }

        $reserve_time = $serviceStartTime;
        $count = $service_duration / 30;
        //时间分段
        $time_arr = [];
        array_push($time_arr, $reserve_time);
        if ($count > 1) {
            for ($i = 0; $i < $count; $i++) {
                $time = $reserve_time + 30 * 60 * ($i + 1);
                array_push($time_arr, $time);
            }
        } else {
            array_push($time_arr, $reserve_time + 30 * 60);
        }
        $check = $scheduleModel->where('user_id', $order['worker_id'])->where('rest_timestamp', 'in', $time_arr)->find();
        if ($check) {
            $this->error('当前时间服务人员在忙~请选择其他时间!', []);
        }

        $data['change_status'] = 1;
        $data['service_start_time'] = $serviceStartTime;
        $data['service_duration'] = $service_duration;
        $data['servicenums'] = $servicenums;
        $res = $this->model->save($data, ["id" => $id]);
        //更新服务人员时间排版
        $req = $scheduleModel->where('order_id', $id)->delete();
        $req = $scheduleModel->orderSchedule($order['worker_id'], $id, $data['service_start_time'], $data['service_duration']);
        //发送消息
        $template = new Wxtemplate();
        $openid = XiserviceUser::where('user_id', $order['worker_id'])->value('mini_openid');
        $sendtemplate = $template->messageData($order, $openid, 'change_time');
        $this->success('操作成功', []);
    }

    /**
     * @ApiTitle (确认订单完成)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/finish)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiParams  (name="service_start_time", type="integer", description="上门时间")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function finish()
    {
        $id = $this->request->request('id');

        $order = $this->model->where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
//        $res = $this->model->changeOrderStatus($id, 'finished');
        $res = $this->model->changeOrderStatus($id, 'quality');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $this->success('操作成功', []);
    }

    /**
     * @ApiTitle (验收订单不通过)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.order/checknoorder)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function checknoorder()
    {
        $id = $this->request->request('id');

        $order = $this->model->where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }

        $res = $this->model->changeOrderStatus($id, 'checknoorder');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $this->success('操作成功', []);
    }

    /**
     * @ApiTitle (评价订单)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiservice.order/comment)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiParams  (name="rate", type="integer", description="评分")
     * @ApiParams  (name="images", type="integer", description="照片")
     * @ApiParams  (name="content", type="integer", description="评论内容")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function comment()
    {
        $id = $this->request->request('id');
        $rate = $this->request->request('rate', 5);
        $images = $this->request->request('images');
        $content = $this->request->request('content');
        $flag = $this->request->request('flag',0);

        // $order = $this->model->where('user_id', $this->auth->id)->where('order_status', '70')->where('id', $id)->find();
        $order = $this->model->where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
        Db::execute('update fa_xiservice_order set unusual=1 where id='.$id);
        $data['order_id'] = $id;
        $data['service_id'] = $order['service_id'];
        $data['staff_id'] = $order['worker_id'];
        $data['user_id'] = $this->auth->id;
        $data['rate'] = $rate;
        $data['images'] = $images;
        $data['content'] = $content;
        $data['flag'] = $flag;

        // echo "<pre>";
        // print_r($data);die;

//unusual

        $commentModel = new \app\common\model\xiservice\Comment();
        $result = $commentModel->allowField(true)->save($data);
        $res = $this->model->changeOrderStatus($id, 'comment');
        if (!$res['status']) {
            $result = $commentModel->where('order_id', $id)->delete();
            $this->error($res['msg']);
        }
        //更新服务人员评分
        $this->success('操作成功', []);
    }

    /**
     * @ApiTitle (申请退款)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiservice.order/refund)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiParams  (name="rate", type="integer", description="评分")
     * @ApiParams  (name="images", type="integer", description="照片")
     * @ApiParams  (name="content", type="integer", description="评论内容")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function refund()
    {
        $id = $this->request->request('id');
        $reason = $this->request->request('reason');
        $images = $this->request->request('images');
        $content = $this->request->request('content');

        $order = $this->model->where('user_id', $this->auth->id)
            ->where('order_status', 40)
            ->where('is_refund', 0)
            ->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
        if ($order['transaction_id']) {
            $wxpayconfig = config('xiservice.wxpayment');
            if (isset($wxpayconfig['apiclient_cert'])) {
                if (!$wxpayconfig['apiclient_cert']) {
                    $this->error('请先配置商户证书!', []);
                }
            } else {
                $this->error('请先配置商户证书!', []);
            }
        }
        $res = false;
        $refundModel = new \app\common\model\xiservice\Refund();
        Db::startTrans();
        try {

            $data['refund_no'] = "RZ" . date('YmdHis') . mt_rand(1000, 9999) . $order['user_id'];
            $data['order_id'] = $id;
            $data['service_id'] = $order['service_id'];
            $data['user_id'] = $this->auth->id;
            $data['refund_money'] = $order['pay_money'];
            $data['refund_reason'] = $reason;
            $data['refund_images'] = $images;
            $data['content'] = $content;

            $result = $refundModel->allowField(true)->save($data);

            $orderdata['is_refund'] = 1;
            $orderdata['refund_id'] = $refundModel->id;
            $res = $this->model->where('id', $id)->update($orderdata);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (!$res) {
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * @ApiTitle (取消申请退款)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiservice.order/cancelrefund)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiParams  (name="rate", type="integer", description="评分")
     * @ApiParams  (name="images", type="integer", description="照片")
     * @ApiParams  (name="content", type="integer", description="评论内容")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function cancelrefund()
    {
        $id = $this->request->request('id');
        $order = $this->model->where('user_id', $this->auth->id)
            ->where('order_status', 40)
            ->where('is_refund', 1)
            ->where('id', $id)->find();
        if (!$order) {
            $this->error('订单状态错误', []);
        }
        $refundModel = new \app\common\model\xiservice\Refund();
        $refund = $refundModel->where('id', $order['refund_id'])->where('status', 0)->find();
        if (!$refund) {
            $this->error('订单信息错误', []);
        }
        $res = false;
        Db::startTrans();
        try {

            $data['status'] = 3;
            $result = $refundModel->allowField(true)->save($data, ["id" => $order['refund_id']]);

            $orderdata['is_refund'] = 0;
            $orderdata['refund_id'] = 0;
            $res = $this->model->where('id', $id)->update($orderdata);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * todo 生成环境必须屏蔽
     * 模拟回调
     */
    public function analog_notify()
    {
        //使用
//        Http::sendAsyncRequest(request()->domain().'/index.php/api/xiservice.order/analog_notify', ['id' => $orderInfo->id]);
//        $this->success('ok');

//        sleep(1);
        $oid = $this->request->param('id');
        $order = $this->model->get($oid);
        $user = XiserviceUser::where('user_id', $order->user_id)->find();
        $config = \addons\xiservice\library\Config::load();
        $xmlArr = [
            'return_code' => 'SUCCESS',
            'result_code' => 'SUCCESS',
            'appid' => $config['app_id'],
            'mch_id' => $config['mch_id'],
            'nonce_str' => mt_rand(10000000, 99999999),
            'sign_type' => 'MD5',
            'openid' => $user['mini_openid'],
            'is_subscribe' => 'N',
            'trade_type' => 'JSAPI',
            'bank_type' => 'CFT',
            'total_fee' => $order->total_money * 100,
            'cash_fee' => $order->pay_money * 100,
            'transaction_id' => str_replace('JZ', '1234', $order->order_no),
            'out_trade_no' => $order->order_no . '_' . mt_rand(100, 999),
            'time_end' => date('YmdHis'),
        ];
        ksort($xmlArr);
        $string = '';
        foreach ($xmlArr as $k => $v) {
            $string .= $k . '=' . $v . '&';
        }
        $string .= 'key=' . $config['key'];
        $xmlArr['sign'] = strtoupper(md5($string));

        $xml = '<xml>';
        foreach ($xmlArr as $k => $v) {
            $xml .= '<' . $k . '>' . $v . '</' . $k . '>';
        }
        $xml .= '</xml>';

        myDump($xml);
        myDump($config['notify_url']);
        $res = Http::post($config['notify_url'], $xml, [
            CURLOPT_HTTPHEADER => [
                'content-type: application/xml'
            ]
        ]);
        dump($res);
    }
        //下单合同
        
}